package com.example.flowable.controller;

import com.example.flowable.model.*;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.runtime.ProcessInstanceQuery;
import org.flowable.idm.api.Group;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping (value = "flowable")
public class FlowableController {

    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private RepositoryService repositoryService; // repositoryService = processEngine.getRepositoryService();
    @Autowired
    private TaskService taskService; // taskService = processEngine.getTaskService();
    @Autowired
    private RuntimeService runtimeService; // runtimeService = processEngine.getRuntimeService();
    @Autowired
    private HistoryService historyService; // historyService = processEngine.getHistoryService();
    @Autowired
    private IdentityService identityService;


    /**
     * 系统流程部署列表（流程定义查询）
     */
    @RequestMapping (value = "deploy/list")
    public ResultDTO<List<ProcessDefinitionDTO>> flowableList() {
        List<ProcessDefinition> pdList = repositoryService.createProcessDefinitionQuery().list();
        List<ProcessDefinitionDTO> list = new ArrayList<>();
        for(ProcessDefinition pd:pdList){
            list.add(new ProcessDefinitionDTO(pd));
        }
        return new ResultDTO<List<ProcessDefinitionDTO>>().buildResultDTO(200, "success", list, list.size());
    }

    /**
     * 查看初始流程图
     */
    @RequestMapping(value = "processImg")
    @ResponseBody
    public void resourceRead(String processDefinitionId, String resType, HttpServletResponse response) throws Exception {
        /** resType取值 “image/png”或“text/xml” **/
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        String resourceName = processDefinition.getDiagramResourceName();
//        if (resType.equals("image/png")) {
//            resourceName = processDefinition.getDiagramResourceName();
//        } else if (resType.equals("text/xml")) {
//            resourceName = processDefinition.getResourceName();
//        }
        InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);
        byte[] b = new byte[1024];
        int len = -1;
        while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
        resourceAsStream.close();
    }

    /**
     * 删除系统部署的流程
     */
    @RequestMapping (value = "deploy/remove")
    public String remove(String id) {
        repositoryService.deleteDeployment(id);
        return "删除成功";
    }

    /**
     * 获取流程实例
     */
    @RequestMapping (value = "instance/list")
    public ResultDTO<List<ProcessInstanceDTO>> instanceList(String userId) {
        ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery();
        if(!StringUtils.isEmpty(userId)){
            query.startedBy(userId);
        }

        List<ProcessInstance> processInstanceList = query.list();
        List<ProcessInstanceDTO> list = new ArrayList<>();
        for (ProcessInstance pi : processInstanceList) {
            list.add(new ProcessInstanceDTO(pi));
        }
        return new ResultDTO<List<ProcessInstanceDTO>>().buildResultDTO(200,"sucess",list, list.size());
    }

    /**
     * 删除流程实例
     */
    @RequestMapping (value = "instance/remove")
    public String removeInstance(@RequestBody Map<String, Object> map) {
        runtimeService.deleteProcessInstance((String) map.get("id"), "删除测试");
        return "删除成功";
    }

    /**
     * 获取任务列表
     */
    @RequestMapping (value = "task/list")
    public ResultDTO<List<TaskDTO>> taskList(String userId, String group) {
        TaskQuery query = taskService.createTaskQuery();
        if(!StringUtils.isEmpty(group)){
            query.taskCandidateGroup(group);
        }else if(!StringUtils.isEmpty(userId)){
            query.taskCandidateOrAssigned(userId);
        }
        List<Task> tasks = query.orderByTaskCreateTime().desc().list();
        List<TaskDTO> list = new ArrayList<>();
        for (Task task : tasks) {
            TaskDTO taskDTO = new TaskDTO(task);
            // 根据task查询ProcessInstance
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            if (processInstance != null) {
                taskDTO.setBusinessKey(processInstance.getBusinessKey());
            }
            list.add(taskDTO);
        }
        return new ResultDTO<List<TaskDTO>>().buildResultDTO(200,"sucess",list, list.size());
    }

    /**
     * 删除任务
     */
    @RequestMapping (value = "task/remove")
    public String removeTask(String id) {
        taskService.deleteTask(id);
        return "删除成功";
    }

    /**
     * 获取历史任务列表
     */
    @RequestMapping (value = "historic/list")
    public ResultDTO<List<HistoricProcessInstanceDTO>> historicTaskList(String userId) {
        HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery();
        if(!StringUtils.isEmpty(userId)){
            query.involvedUser(userId);
        }
        query.finished();
        List<HistoricProcessInstance> hpis = query.orderByProcessInstanceEndTime().desc().list();
        List<HistoricProcessInstanceDTO> list = new ArrayList<>();
        for (HistoricProcessInstance hpi : hpis) {
            list.add(new HistoricProcessInstanceDTO(hpi));
        }
        return new ResultDTO<List<HistoricProcessInstanceDTO>>().buildResultDTO(200,"sucess",list, list.size());
    }

    /**
     * 删除历史任务
     */
    @RequestMapping (value = "historic/remove")
    public String removeHistoricTask(@RequestBody Map<String, Object> map) {
        historyService.deleteHistoricProcessInstance((String) map.get("id"));
        return "删除成功";
    }

    /**
     * 生成正在办理的流程图
     *
     * @param processInstanceId 流程实例ID
     */
    @RequestMapping(value = "processDiagram")
    public void genProcessDiagram(HttpServletResponse httpServletResponse, String processInstanceId) throws Exception {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();

        //流程走完的不显示图
        if (pi == null) {
            return;
        }
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).list().get(0);
        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
        String InstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(InstanceId)
                .list();

        //得到正在执行的Activity的Id
        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 2.0, true);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 生成正在办理的流程图
     *
     * @param processInstanceId 流程实例ID
     */
    @RequestMapping(value = "processDiagramEnd")
    public void genProcessDiagramEnd(HttpServletResponse httpServletResponse, String processInstanceId) throws Exception {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String procDefId;
        //流程走完的不显示图
        if (processInstance == null) {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            procDefId = historicProcessInstance.getProcessDefinitionId();
        } else {
            procDefId = processInstance.getProcessDefinitionId();
        }
        BpmnModel bpmnModel = repositoryService.getBpmnModel(procDefId);
        DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator(); // 创建默认的流程图生成器
        String imageType = "png"; // 生成图片的类型
        List<String> highLightedActivities = new ArrayList<>(); // 高亮节点集合
        List<String> highLightedFlows = new ArrayList<>(); // 高亮连线集合
        List<HistoricActivityInstance> hisActInsList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .list(); // 查询所有历史节点信息
        hisActInsList.forEach(historicActivityInstance -> { // 遍历
            if("sequenceFlow".equals(historicActivityInstance.getActivityType())) {
                // 添加高亮连线
                highLightedFlows.add(historicActivityInstance.getActivityId());
            } else {
                // 添加高亮节点
                highLightedActivities.add(historicActivityInstance.getActivityId());
            }
        });
        String activityFontName = "宋体"; // 节点字体
        String labelFontName = "微软雅黑"; // 连线标签字体
        String annotationFontName = "宋体"; // 连线标签字体
        ClassLoader customClassLoader = null; // 类加载器
        double scaleFactor = 1.0d; // 比例因子，默认即可
        boolean drawSequenceFlowNameWithNoLabelDI = true; // 不设置连线标签不会画
        // 生成图片
        InputStream inputStream = defaultProcessDiagramGenerator.generateDiagram(bpmnModel, imageType, highLightedActivities
                , highLightedFlows, activityFontName, labelFontName, annotationFontName, customClassLoader,
                scaleFactor, drawSequenceFlowNameWithNoLabelDI); // 获取输入流
        // 输出资源内容到相应对象
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b, 0, 1024)) != -1) {
            httpServletResponse.getOutputStream().write(b, 0, len);
        }
        inputStream.close();
    }


    @RequestMapping(value = "user/add")
    @ResponseBody
    public ResultDTO<Void> useradd(@RequestBody User user) {
        UserEntityImpl flowableuser = new UserEntityImpl();
        flowableuser.setId(String.valueOf(user.getId()));
        flowableuser.setDisplayName(user.getUserName());
        flowableuser.setPassword("123");
        flowableuser.setRevision(0);
        identityService.saveUser(flowableuser);
        // 用户添加到组里
        identityService.createMembership(String.valueOf(user.getId()), String.valueOf(user.getRoleId()));
        return new ResultDTO<Void>().buildResultDTO(200,"sucess",null,null);
    }

    @RequestMapping(value = "user/list")
    @ResponseBody
    public ResultDTO<List<User>> userlist() {
        List<org.flowable.idm.api.User> list = identityService.createUserQuery().list();
        List<User> users = new ArrayList<>();
        for (org.flowable.idm.api.User flowableuser:list) {
            User user = new User();
            user.setId(Integer.valueOf(flowableuser.getId()));
            user.setUserName(flowableuser.getDisplayName());
            // 根据用户查询组
            Group group = identityService.createGroupQuery().groupMember(flowableuser.getId()).singleResult();
            if (group != null) {
                user.setRoleId(Integer.valueOf(group.getId()));
            }
            users.add(user);
        }
        return new ResultDTO<List<User>>().buildResultDTO(200,"sucess",users, users.size());
    }

    @RequestMapping(value = "user/remove")
    @ResponseBody
    public ResultDTO<Void> userremove(@RequestBody User user) {
        identityService.deleteUser(String.valueOf(user.getId()));
        return new ResultDTO<Void>().buildResultDTO(200,"sucess",null,null);
    }


    @RequestMapping(value = "role/add")
    @ResponseBody
    public ResultDTO<Void> roleadd(@RequestBody Role role) {
        GroupEntityImpl g = new GroupEntityImpl();
        g.setName(role.getRoleName());
        g.setId(String.valueOf(role.getId()));
        g.setRevision(0);
        identityService.saveGroup(g);
        return new ResultDTO<Void>().buildResultDTO(200,"sucess",null,null);
    }

    @RequestMapping(value = "role/list")
    @ResponseBody
    public ResultDTO<List<Role>> rolelist() {
        List<Group> groupList = identityService.createGroupQuery().list();
        List<Role> roles = new ArrayList<>();
        for (Group group:groupList) {
            Role role = new Role();
            role.setId(Integer.valueOf(group.getId()));
            role.setRoleName(group.getName());
            roles.add(role);
        }
        return new ResultDTO<List<Role>>().buildResultDTO(200,"sucess",roles, roles.size());
    }

    @RequestMapping(value = "role/remove")
    @ResponseBody
    public ResultDTO<Void> roleremove(@RequestBody Role role) {
        identityService.deleteGroup(String.valueOf(role.getId()));
        return new ResultDTO<Void>().buildResultDTO(200,"sucess",null,null);
    }
}
